import React, { useEffect, useState, useRef } from 'react'
import {
  Tabs,
  Input,
  List,
  Avatar,
  Row,
  Col,
  Space,
  AutoComplete,
  Divider,
  Select,
  Button,
  message,
  Skeleton
} from 'antd'
import {
  ProCard,
  ProDescriptions,
  ProTable,
  TableDropdown,
  ProFormText,
  ProForm,
  ProFormTextArea,
  ProFormDependency,
  ProFormSelect,
  FooterToolbar,
} from '@ant-design/pro-components';
import { PlusOutlined } from '@ant-design/icons';
import {
  reqPatientList,
  reqDetal,
  reqUpdate,
  reqPulseUpdate,
  reqPulseDetail,
  reqPulseList,
  reqQuestionTermList,
  reqIllnessList
} from '@/services/basicConsultation';
import styles from './index.module.less'

const IllnessList = ({
  user,
  upDataInfo,
  readonly = false
}) => {
  const [formObj] = ProForm.useForm()

  const [data, setData] = useState<any>([])

  const [initialValues, setinitialValues] = useState<any>(null)

  function arrayFormatOptions(array: []) {
    if (!Array.isArray(array)) return []
    return array.map((item) => ({
      label: item?.name,
      value: item?.name,
    }))
  }

  async function init() {
    try {
      const res = await reqIllnessList({
        pageNum: 1,
        pageSize: 10,
        illnessType: 2
      })
      console.log('病种病名列表信息 :>> ', res?.data);
      if (res?.resultCode == '00000000') {
        setData(res?.data?.result)
      } else {
        message.error(`病种病名列表信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error('病种病名列表信息出错！', error)
      console.log('病种病名列表信息出错！ :>> ', error);
    }
  }


  useEffect(() => {
    if (user?.id) {
      init()
      console.log('object :>> ', {
        illnessNameHistory: user?.illnessNameHistory?.split(','),
        medicalHistory: user?.medicalHistory
      });
      setinitialValues({
        tabooMedication: user?.tabooMedication,
        previouslyUsedMedication: user?.previouslyUsedMedication,
        illnessNameHistory: user?.illnessNameHistory?.split(','),
        medicalHistory: user?.medicalHistory
      })
    }
  }, [user])


  async function handleAdd(values) {
    console.log('输入病史 :>> ', values);
    upDataInfo && upDataInfo({
      ...values,
      illnessNameHistory: values?.illnessNameHistory?.join(',')
    })
  }

  const [selectList, setSelectList] = useState([
    '痛症', '下心痞'
  ]);
  const inputRef = useRef(null);

  const [name, setName] = useState('');

  const onNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };

  const addItem = (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => {
    e.preventDefault();
    setSelectList([...selectList, name || `New item ${+new Date()}`]);
    setName('');
    setTimeout(() => {
      inputRef.current?.focus();
    }, 0);
  };

  return (
    initialValues === null && user?.id ?
      <Skeleton active paragraph={{ rows: 6 }} /> :
      <ProForm
        form={formObj}
        initialValues={initialValues}
        onFinish={(values): Promise<any> => handleAdd(values)}
        readonly={readonly}
        submitter={!readonly && {
          // 配置按钮文本
          searchConfig: {
            submitText: '保存',
            resetText: '重置',
          },
          // 配置按钮的属性
          // resetButtonProps: {
          //   style: {
          //     // 隐藏重置按钮
          //     display: 'none',
          //   },
          // },
          submitButtonProps: {},

          // render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,

          // 完全自定义整个区域
          render: (props, doms) => {
            console.log(props);
            return [
              <Button
                type='primary'
                key="submit"
                onClick={() => props.form?.submit?.()}
              >
                保存
              </Button>,
              <Button
                key="rest"
                onClick={() => props.form?.resetFields()}
              >
                重置
              </Button>,
            ];
          },
        }}
      >
        <Row gutter={24}>
          {/* <Col span={24}>
            <ProFormSelect
              style={{ width: '100%' }}
              placeholder="请选择病症"
              label="病症"
              name='illnessNameHistory'
              // searchOnFocus={true}
              fieldProps={{
                mode: "multiple",
                maxTagCount: 2,
                dropdownClassName: 'test222',
                dropdownRender: (menu) => (
                  <>
                    <>{console.log('menu :>> ', menu)}</>
                    {menu}
                  </>
                )
              }}
              options={arrayFormatOptions(data)}
            />
          </Col> */}
          <Col span={24}>
            <ProFormText name="tabooMedication" label="禁忌药" placeholder="请输入禁忌药" />
          </Col>
          <Col span={24}>
            <ProFormText name="previouslyUsedMedication" label="曾用药" placeholder="请输入曾用药" />
          </Col>
          <Col span={24}>
            <ProFormTextArea
              name="medicalHistory"
              label="问诊"
              placeholder="请输入问诊"
              help={!readonly && <div className={styles.red}>怎么治疗的，过去的健康情况等。</div>}
            />
          </Col>
        </Row>
      </ProForm>
  )
}


export default IllnessList